package main

import (
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"regexp"
	"strconv"
	"strings"
)

func main() {
	if len(os.Args) < 2 {
		log.Fatalln("Используте: ./start имя_файла_с_исходными_данными имя_файла_с_результатами")
	}
	inFileName := os.Args[1]
	var outFileName string

	if len(os.Args) == 2 {
		outFileName = "out.txt"
	} else {
		outFileName = os.Args[2]
	}
	inFile, err := os.Open(inFileName)
	if err != nil {
		log.Fatalln(err)
	}
	content, err := io.ReadAll(inFile)
	if err != nil {
		inFile.Close()
		log.Fatalln(err)
	}
	inData := strings.Split(string(content), "\n")

	err = os.Remove(outFileName)
	if err != nil {
		log.Println(err)
	}
	outFile, err := os.OpenFile(outFileName, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0o777)
	if err != nil {
		inFile.Close()
		log.Fatalln(err)
	}
	defer outFile.Close()

	for _, in := range inData {
		out, err := processing(in)
		if err != nil {
			log.Println(err)
			continue
		}
		_, err = outFile.WriteString(out + "\n")
		if err != nil {
			log.Println(err)
			break
		}
	}
	inFile.Close()
}

func processing(in string) (string, error) {
	r := regexp.MustCompile(`(\d+)([+ -])(\d+)=\?`)
	splitIn := r.FindStringSubmatch(in)
	if len(splitIn) < 3 {
		return "", errors.New("неверный шаблон ввода")
	}
	operand1, err := strconv.Atoi(splitIn[1])
	if err != nil {
		return "", err
	}
	operation := splitIn[2]
	operand2, err := strconv.Atoi(splitIn[3])
	if err != nil {
		return "", err
	}
	var res int
	switch operation {
	case "+":
		res = operand1 + operand2
	case "-":
		res = operand1 - operand2
	default:
		return "", errors.New("неподдерживаемая математическая операция")
	}
	return fmt.Sprintf("%d%s%d=%d", operand1, operation, operand2, res), nil
}
